import React, { useState, useEffect } from 'react';
import { motion, AnimatePresence } from 'framer-motion';
import { cn } from '@/lib/utils';
import { useTheme } from '@/hooks/useTheme';
import api, { ApiResponse } from '@/services/api';
import { toast } from 'sonner';
import { createPatch } from 'diff';
import VersionDiff from './VersionDiff';

interface VersionRecord {
  versionId: string;
  docId: string;
  docContent: string;
  diffContent: string;
  isCurrent: boolean;
  contentHash: string;
  createUser: string;
  createTime: string;
}

interface VersionHistoryModalProps {
  isOpen: boolean;
  onClose: () => void;
  docId: string;
  docTitle: string;
  onVersionRestored?: () => void;
}

export default function VersionHistoryModal({ 
  isOpen, 
  onClose, 
  docId, 
  docTitle,
  onVersionRestored 
}: VersionHistoryModalProps) {
  const { isDark } = useTheme();
  
  const [versions, setVersions] = useState<VersionRecord[]>([]);
  const [isLoading, setIsLoading] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [totalPages, setTotalPages] = useState(1);
  const [selectedVersion, setSelectedVersion] = useState<VersionRecord | null>(null);
  const [showVersionDetail, setShowVersionDetail] = useState(false);
  const [isRestoring, setIsRestoring] = useState(false);

  // 加载版本历史
  const loadVersionHistory = async (pageNo: number = 1) => {
    if (!docId) return;
    
    try {
      setIsLoading(true);
      const res: ApiResponse = await api({
        url: `/doc/version/pageVersion?pageNo=${pageNo}&pageSize=10`,
        method: 'post',
        data: { docId },
        timeout: 10000
      });

      if (res && res.success && res.data) {
        setVersions(res.data.records || []);
        setTotalPages(res.data.totalPage || 1);
        setCurrentPage(pageNo);
      } else {
        throw new Error(res?.message || '获取版本历史失败');
      }
    } catch (error: any) {
      console.error('获取版本历史失败:', error);
      toast.error(error.message || '获取版本历史失败');
    } finally {
      setIsLoading(false);
    }
  };

  // 恢复版本
  const handleRestoreVersion = async (versionId: string) => {
    try {
      setIsRestoring(true);
      const res: ApiResponse = await api({
        url: '/doc/version/rebackVersion',
        method: 'post',
        data: { versionId },
        timeout: 10000
      });

      if (res && res.success) {
        toast.success('版本恢复成功');
        onVersionRestored?.();
        onClose();
      } else {
        throw new Error(res?.message || '版本恢复失败');
      }
    } catch (error: any) {
      console.error('版本恢复失败:', error);
      toast.error(error.message || '版本恢复失败');
    } finally {
      setIsRestoring(false);
    }
  };

  // 格式化时间
  const formatTime = (timeStr: string) => {
    try {
      const date = new Date(timeStr);
      return date.toLocaleString('zh-CN');
    } catch {
      return timeStr;
    }
  };

  // 解析 diff 内容
  const parseDiffContent = (diffContent: string) => {
    if (!diffContent) return { additions: [], deletions: [] };
    
    const lines = diffContent.split('\n');
    const additions: string[] = [];
    const deletions: string[] = [];
    
    lines.forEach(line => {
      if (line.startsWith('+') && !line.startsWith('+++')) {
        additions.push(line.substring(1));
      } else if (line.startsWith('-') && !line.startsWith('---')) {
        deletions.push(line.substring(1));
      }
    });
    
    return { additions, deletions };
  };

  // 当弹窗打开时加载数据
  useEffect(() => {
    if (isOpen && docId) {
      loadVersionHistory(1);
    }
  }, [isOpen, docId]);

  // 版本详情弹窗
  const VersionDetailModal = () => {
    if (!selectedVersion) return null;
    // 找到当前版本在 versions 列表中的索引
    const idx = versions.findIndex(v => v.versionId === selectedVersion.versionId);
    // 上一个版本内容（如果有）
    const prevContent = idx < versions.length - 1 ? versions[idx + 1].docContent : '';
    // 当前版本内容
    const currContent = selectedVersion.docContent;
    return (
      <AnimatePresence>
        {showVersionDetail && (
          <motion.div
            key="detail-motion"
            initial={{ opacity: 0 }}
            animate={{ opacity: 1 }}
            exit={{ opacity: 0 }}
            className="fixed inset-0 bg-black/50 backdrop-blur-sm z-[9999] flex items-center justify-center p-4"
            onClick={() => setShowVersionDetail(false)}
          >
            <motion.div
              key="detail-modal-content"
              initial={{ scale: 0.9, opacity: 0 }}
              animate={{ scale: 1, opacity: 1 }}
              exit={{ scale: 0.9, opacity: 0 }}
              className={cn(
                "w-full max-w-4xl max-h-[90vh] overflow-hidden rounded-2xl shadow-2xl flex flex-col",
                isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
              )}
              onClick={(e) => e.stopPropagation()}
            >
              {/* 头部 */}
              <div className={cn(
                "flex items-center justify-between p-4 border-b",
                isDark ? "border-gray-700" : "border-gray-200"
              )}>
                <h3 className={cn(
                  "text-lg font-semibold",
                  isDark ? "text-white" : "text-gray-900"
                )}>
                  <i className="fa-solid fa-history mr-2 text-blue-500"></i>
                  版本详情
                </h3>
                <button
                  onClick={() => setShowVersionDetail(false)}
                  className={cn(
                    "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                    isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                  )}
                >
                  <i className="fa-solid fa-times"></i>
                </button>
              </div>

              {/* 版本信息 */}
              <div className={cn(
                "p-4 border-b",
                isDark ? "border-gray-700 bg-gray-900/50" : "border-gray-200 bg-gray-50"
              )}>
                <div className="grid grid-cols-2 gap-4 text-sm">
                  <div>
                    <span className={cn(
                      "font-medium",
                      isDark ? "text-gray-300" : "text-gray-600"
                    )}>创建时间：</span>
                    <span className={cn(
                      isDark ? "text-gray-200" : "text-gray-800"
                    )}>{formatTime(selectedVersion.createTime)}</span>
                  </div>
                  <div>
                    <span className={cn(
                      "font-medium",
                      isDark ? "text-gray-300" : "text-gray-600"
                    )}>创建用户：</span>
                    <span className={cn(
                      isDark ? "text-gray-200" : "text-gray-800"
                    )}>{selectedVersion.createUser}</span>
                  </div>
                  <div>
                    <span className={cn(
                      "font-medium",
                      isDark ? "text-gray-300" : "text-gray-600"
                    )}>版本ID：</span>
                    <span className={cn(
                      "font-mono text-xs",
                      isDark ? "text-gray-200" : "text-gray-800"
                    )}>{selectedVersion.versionId}</span>
                  </div>
                  <div>
                    <span className={cn(
                      "font-medium",
                      isDark ? "text-gray-300" : "text-gray-600"
                    )}>内容哈希：</span>
                    <span className={cn(
                      "font-mono text-xs",
                      isDark ? "text-gray-200" : "text-gray-800"
                    )}>{selectedVersion.contentHash}</span>
                  </div>
                </div>
              </div>

              {/* diff 对比视图 */}
              <div className="flex-1 min-h-0 overflow-y-auto p-4 font-mono text-sm bg-white dark:bg-gray-900">
                <VersionDiff oldText={prevContent} newText={currContent} />
              </div>

              {/* 底部操作 */}
              <div className={cn(
                "flex items-center justify-between p-4 border-t",
                isDark ? "border-gray-700" : "border-gray-200"
              )}>
                <div className="text-sm text-gray-500">
                  点击外部区域关闭
                </div>
                <div className="flex space-x-2">
                  <button
                    onClick={() => setShowVersionDetail(false)}
                    className={cn(
                      "px-4 py-2 rounded-lg font-medium transition-colors",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-200" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                    )}
                  >
                    关闭
                  </button>
                  <button
                    onClick={() => handleRestoreVersion(selectedVersion.versionId)}
                    disabled={isRestoring}
                    className={cn(
                      "px-4 py-2 rounded-lg font-medium transition-colors",
                      isRestoring
                        ? "opacity-50 cursor-not-allowed"
                        : "",
                      isDark 
                        ? "bg-blue-600 hover:bg-blue-700 text-white" 
                        : "bg-blue-500 hover:bg-blue-600 text-white"
                    )}
                  >
                    {isRestoring ? (
                      <>
                        <i className="fa-solid fa-spinner fa-spin mr-2"></i>
                        恢复中...
                      </>
                    ) : (
                      <>
                        <i className="fa-solid fa-undo mr-2"></i>
                        恢复到此版本
                      </>
                    )}
                  </button>
                </div>
              </div>
            </motion.div>
          </motion.div>
        )}
      </AnimatePresence>
    );
  };

  return (
    <AnimatePresence>
      {isOpen && (
        <motion.div
          key="main-modal"
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0 }}
          className="fixed inset-0 bg-black/50 backdrop-blur-sm z-50 flex items-center justify-center p-4"
          onClick={onClose}
        >
          <motion.div
            key="main-modal-content"
            initial={{ scale: 0.9, opacity: 0, y: 20 }}
            animate={{ scale: 1, opacity: 1, y: 0 }}
            exit={{ scale: 0.9, opacity: 0, y: 20 }}
            className={cn(
              "w-full max-w-4xl max-h-[90vh] overflow-hidden rounded-2xl shadow-2xl",
              isDark ? "bg-gray-800 border border-gray-700" : "bg-white border border-gray-200"
            )}
            onClick={(e) => e.stopPropagation()}
          >
            {/* 头部 */}
            <div className={cn(
              "flex items-center justify-between p-4 border-b",
              isDark ? "border-gray-700" : "border-gray-200"
            )}>
              <h3 className={cn(
                "text-lg font-semibold",
                isDark ? "text-white" : "text-gray-900"
              )}>
                <i className="fa-solid fa-history mr-2 text-blue-500"></i>
                历史版本 - {docTitle}
              </h3>
              <button
                onClick={onClose}
                className={cn(
                  "w-8 h-8 rounded-full flex items-center justify-center transition-colors",
                  isDark ? "hover:bg-gray-700 text-gray-400" : "hover:bg-gray-100 text-gray-600"
                )}
              >
                <i className="fa-solid fa-times"></i>
              </button>
            </div>

            {/* 内容 */}
            <div className="flex-1 overflow-hidden">
              {isLoading ? (
                <div className="flex items-center justify-center h-64">
                  <div className="flex flex-col items-center space-y-4">
                    <div className={cn(
                      "w-12 h-12 rounded-full flex items-center justify-center",
                      isDark ? "bg-blue-600/20" : "bg-blue-500/20"
                    )}>
                      <i className={cn(
                        "fa-solid fa-spinner fa-spin text-xl",
                        isDark ? "text-blue-400" : "text-blue-500"
                      )}></i>
                    </div>
                    <span className="text-gray-500">加载版本历史中...</span>
                  </div>
                </div>
              ) : (
                <div className="p-4">
                  {versions.length === 0 ? (
                    <div className="flex flex-col items-center justify-center h-64 text-gray-500">
                      <i className="fa-solid fa-history text-4xl mb-4 opacity-50"></i>
                      <span>暂无版本历史</span>
                    </div>
                  ) : (
                    <div className="space-y-3">
                      {versions.map((version, index) => (
                        <motion.div
                          key={version.versionId || `version-${index}`}
                          initial={{ opacity: 0, y: 20 }}
                          animate={{ opacity: 1, y: 0 }}
                          transition={{ delay: index * 0.1 }}
                          className={cn(
                            "p-4 rounded-lg border transition-colors",
                            isDark ? "border-gray-700 hover:bg-gray-700/50" : "border-gray-200 hover:bg-gray-50",
                            version.isCurrent && (isDark ? "bg-blue-900/20 border-blue-600" : "bg-blue-50 border-blue-300")
                          )}
                        >
                          <div className="flex items-center justify-between">
                            <div className="flex items-center space-x-3">
                              <div className={cn(
                                "w-8 h-8 rounded-full flex items-center justify-center text-sm font-semibold",
                                version.isCurrent
                                  ? (isDark ? "bg-blue-600 text-white" : "bg-blue-500 text-white")
                                  : (isDark ? "bg-gray-600 text-gray-200" : "bg-gray-500 text-white")
                              )}>
                                {index + 1}
                              </div>
                              <div>
                                <div className="flex items-center space-x-2">
                                  <span className={cn(
                                    "font-medium",
                                    isDark ? "text-white" : "text-gray-900"
                                  )}>
                                    版本 {index + 1}
                                  </span>
                                  {version.isCurrent && (
                                    <span className={cn(
                                      "px-2 py-1 rounded-full text-xs font-medium",
                                      isDark ? "bg-blue-600 text-white" : "bg-blue-500 text-white"
                                    )}>
                                      当前版本
                                    </span>
                                  )}
                                </div>
                                <div className={cn(
                                  "text-sm",
                                  isDark ? "text-gray-400" : "text-gray-600"
                                )}>
                                  {formatTime(version.createTime)} · {version.createUser}
                                </div>
                              </div>
                            </div>
                            <div className="flex items-center space-x-2">
                              <button
                                onClick={() => {
                                  setSelectedVersion(version);
                                  setShowVersionDetail(true);
                                }}
                                className={cn(
                                  "px-3 py-1 rounded text-sm transition-colors",
                                  isDark 
                                    ? "bg-gray-700 hover:bg-gray-600 text-gray-200" 
                                    : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                                )}
                              >
                                <i className="fa-solid fa-eye mr-1"></i>
                                详情
                              </button>
                              {!version.isCurrent && (
                                <button
                                  onClick={() => handleRestoreVersion(version.versionId)}
                                  disabled={isRestoring}
                                  className={cn(
                                    "px-3 py-1 rounded text-sm transition-colors",
                                    isRestoring
                                      ? "opacity-50 cursor-not-allowed"
                                      : "",
                                    isDark 
                                      ? "bg-orange-600 hover:bg-orange-700 text-white" 
                                      : "bg-orange-500 hover:bg-orange-600 text-white"
                                  )}
                                >
                                  {isRestoring ? (
                                    <i className="fa-solid fa-spinner fa-spin mr-1"></i>
                                  ) : (
                                    <i className="fa-solid fa-undo mr-1"></i>
                                  )}
                                  恢复
                                </button>
                              )}
                            </div>
                          </div>
                        </motion.div>
                      ))}
                    </div>
                  )}
                </div>
              )}
            </div>

            {/* 分页 */}
            {totalPages > 1 && (
              <div className={cn(
                "flex items-center justify-between p-4 border-t",
                isDark ? "border-gray-700" : "border-gray-200"
              )}>
                <div className="text-sm text-gray-500">
                  共 {totalPages} 页
                </div>
                <div className="flex items-center space-x-2">
                  <button
                    onClick={() => loadVersionHistory(currentPage - 1)}
                    disabled={currentPage <= 1}
                    className={cn(
                      "px-3 py-1 rounded text-sm transition-colors",
                      currentPage <= 1
                        ? "opacity-50 cursor-not-allowed"
                        : "",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-200" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                    )}
                  >
                    <i className="fa-solid fa-chevron-left mr-1"></i>
                    上一页
                  </button>
                  <span className={cn(
                    "px-3 py-1 text-sm",
                    isDark ? "text-gray-300" : "text-gray-700"
                  )}>
                    {currentPage} / {totalPages}
                  </span>
                  <button
                    onClick={() => loadVersionHistory(currentPage + 1)}
                    disabled={currentPage >= totalPages}
                    className={cn(
                      "px-3 py-1 rounded text-sm transition-colors",
                      currentPage >= totalPages
                        ? "opacity-50 cursor-not-allowed"
                        : "",
                      isDark 
                        ? "bg-gray-700 hover:bg-gray-600 text-gray-200" 
                        : "bg-gray-200 hover:bg-gray-300 text-gray-700"
                    )}
                  >
                    下一页
                    <i className="fa-solid fa-chevron-right ml-1"></i>
                  </button>
                </div>
              </div>
            )}
          </motion.div>
        </motion.div>
      )}

      {showVersionDetail && <VersionDetailModal key="detail-modal" />}
    </AnimatePresence>
  );
} 